package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient1 {
    String serverIp;
    int serverPort;
    DatagramSocket socket;

    UdpEchoClient1(String ip, int port) throws SocketException {
        socket = new DatagramSocket();
        serverPort = port;
        serverIp = ip;
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("输入请求");
            System.out.print("->");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);
            //用来接收的数据报
            DatagramPacket receivePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(receivePacket);
            String receive = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println(receive);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient1 client1 = new UdpEchoClient1("127.0.0.1", 1314);
        client1.start();
    }
}
